// 简单封装jquery ajax
function ajaxReturn(url, data, succ_func, fail_func, options) {
    options = typeof options === 'undefined' ? {} : options;
    $.ajax({
        cache: true,
        type: options.hasOwnProperty('method') ? options['method'] : 'POST',
        async: options.hasOwnProperty('async') ? options['async'] : true,
        url: url,
        data: data,
        // dataType: 'json',
        error: fail_func,
        success: succ_func
    });
}

// 获取url参数
function getParams(k, st) {
    var search = {}, es, key;
    $.each(st.split('&'), function (i, s) {
        es = s.split('=');
        key = es[0];
        if (key === k) {
            search = es[1];
            return false;
        }
        search[key] = es[1];
    });
    return search;
}

function oAuth(callback) {
    // 请求授权地址
    var server = options['server'],
        auth = options['auth'],
        // 授权完成跳转地址
        callbacks = options['callback'],
        c_url = location.href,
        f_code = c_url.indexOf('code');

    if (f_code === -1) {
        ajaxReturn(server, { callback: callbacks }, function (json) {
            // 已授权
            callback();
        }, function (json) {
            // 未授权
            if (json.status === 401) {
                location.href = json.responseText;
            } else {
                console.log(json)
                alert("系统异常，请稍后再试！");
            }
        }, { async: false, method: 'GET' });
    }
    else if (f_code > -1) {
        var code = getParams('code', c_url.substring(f_code)),
            state = getParams('state', c_url.substring(c_url.indexOf('state')));
        ajaxReturn(auth, { code: code, state: state }, function (json) {
            // 已授权
            location.href = callbacks;
        }, function (json) {
            console.log('授权失败');
        }, { method: 'GET' });
    }
}